package db

import (
	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
	"notabug.org/alimiracle/my-website-api/models"
)

type Database struct {
	db *gorm.DB
}

func Init() Database {

	var database Database

	var err error

	database.db, err = gorm.Open(sqlite.Open("alimiracle.db"), &gorm.Config{})
	if err != nil {
		panic("failed to connect database")
	}

	// Migrate the schema
	database.db.AutoMigrate(&models.Project{})
	database.db.AutoMigrate(&models.Skill{})
	database.db.AutoMigrate(&models.Job{})
	database.db.AutoMigrate(&models.Contact{})
	database.db.AutoMigrate(&models.User{})

	return database
}
func (self Database) FindAll(model any) {

	self.db.Find(model)
}
func (self Database) Create(model any) error {

	result := self.db.Create(model)
	return result.Error
}
func (self Database) Update(model any, id string) error {
	result := self.db.First(model, id)
	if result.Error != nil {
		return result.Error

	}
	self.db.Save(model)
	return result.Error
}
func (self Database) Delete(model any, id string) error {
	result := self.db.First(model, id)
	if result.Error != nil {
		return result.Error

	}
	self.db.Delete(model)
	return result.Error
}
func (self Database) FindUser(name string, model any) error {
	result := self.db.Where("name = ?", name).First(model)
	return result.Error
}
func (self Database) AddAdmin() {
	var count_users []models.User
	user := models.User{Name: "admin", Pass: "admin", Is_admin: true}
	self.FindAll(&count_users)

	if len(count_users) == 0 {
		self.Create(&user)
	}

}
